@using DaoHang.Services
@using DaoHang.Models
@namespace DaoHang.Components.Admin
@inject IIconService IconService
@inject IDataSeedService DataSeedService
@inject IJSRuntime JSRuntime
@inject ILogger<IconManagement> Logger

<div class="card">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="bi bi-image me-2"></i>图标管理
        </h5>
    </div>
    <div class="card-body">
        <div class="row">
            <!-- 操作面板 -->
            <div class="col-md-6 mb-4">
                <div class="card border-info h-100">
                    <div class="card-header bg-info text-white">
                        <h6 class="mb-0"><i class="bi bi-gear me-2"></i>批量操作</h6>
                    </div>
                    <div class="card-body">
                        <div class="d-grid gap-3">
                            <button class="btn btn-primary" @onclick="BatchUpdateIcons" disabled="@isUpdating">
                                @if (isUpdating)
                                {
                                    <span class="spinner-border spinner-border-sm me-2" role="status"></span>
                                    <span>更新中...</span>
                                }
                                else
                                {
                                    <i class="bi bi-arrow-repeat me-2"></i>
                                    <span>一键更新所有图标</span>
                                }
                            </button>
                            
                            <button class="btn btn-info" @onclick="UpdateDefaultWebsiteIcons" disabled="@isUpdatingDefault">
                                @if (isUpdatingDefault)
                                {
                                    <span class="spinner-border spinner-border-sm me-2" role="status"></span>
                                    <span>更新中...</span>
                                }
                                else
                                {
                                    <i class="bi bi-cloud-download me-2"></i>
                                    <span>更新默认网站图标</span>
                                }
                            </button>
                            
                            <button class="btn btn-warning" @onclick="CleanupUnusedIcons" disabled="@isCleaning">
                                @if (isCleaning)
                                {
                                    <span class="spinner-border spinner-border-sm me-2" role="status"></span>
                                    <span>清理中...</span>
                                }
                                else
                                {
                                    <i class="bi bi-trash me-2"></i>
                                    <span>清理未使用图标</span>
                                }
                            </button>
                            
                            <button class="btn btn-success" @onclick="GenerateDefaultIcon" disabled="@isGenerating">
                                @if (isGenerating)
                                {
                                    <span class="spinner-border spinner-border-sm me-2" role="status"></span>
                                    <span>生成中...</span>
                                }
                                else
                                {
                                    <i class="bi bi-plus-circle me-2"></i>
                                    <span>生成默认图标</span>
                                }
                            </button>
                        </div>

                        @if (!string.IsNullOrEmpty(operationMessage))
                        {
                            <div class="alert @(isOperationSuccess ? "alert-success" : "alert-danger") mt-3">
                                <i class="bi @(isOperationSuccess ? "bi-check-circle" : "bi-exclamation-triangle") me-2"></i>
                                @operationMessage
                            </div>
                        }
                    </div>
                </div>
            </div>

            <!-- 统计信息 -->
            <div class="col-md-6 mb-4">
                <div class="card border-success h-100">
                    <div class="card-header bg-success text-white">
                        <h6 class="mb-0"><i class="bi bi-bar-chart me-2"></i>统计信息</h6>
                    </div>
                    <div class="card-body">
                        @if (updateResult != null)
                        {
                            <div class="row g-3">
                                <div class="col-6">
                                    <div class="text-center p-3 bg-light rounded">
                                        <div class="fs-4 fw-bold text-primary">@updateResult.TotalCount</div>
                                        <small class="text-muted">总网站数</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center p-3 bg-light rounded">
                                        <div class="fs-4 fw-bold text-success">@updateResult.SuccessCount</div>
                                        <small class="text-muted">成功更新</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center p-3 bg-light rounded">
                                        <div class="fs-4 fw-bold text-warning">@updateResult.DefaultIconCount</div>
                                        <small class="text-muted">使用默认图标</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center p-3 bg-light rounded">
                                        <div class="fs-4 fw-bold text-danger">@updateResult.FailureCount</div>
                                        <small class="text-muted">更新失败</small>
                                    </div>
                                </div>
                            </div>
                            
                            @if (updateResult.SuccessRate > 0)
                            {
                                <div class="mt-3">
                                    <label class="form-label">成功率</label>
                                    <div class="progress">
                                        <div class="progress-bar @GetProgressBarClass(updateResult.SuccessRate)" 
                                             role="progressbar" 
                                             style="width: @(updateResult.SuccessRate)%">
                                            @($"{updateResult.SuccessRate:F1}%")
                                        </div>
                                    </div>
                                </div>
                            }
                        }
                        else
                        {
                            <div class="text-center py-4">
                                <i class="bi bi-info-circle text-muted" style="font-size: 2rem;"></i>
                                <p class="text-muted mt-2">执行批量更新后将显示统计信息</p>
                            </div>
                        }
                    </div>
                </div>
            </div>

            <!-- 下载策略说明 -->
            <div class="col-12 mb-4">
                <div class="card border-primary">
                    <div class="card-header bg-primary text-white">
                        <h6 class="mb-0"><i class="bi bi-info-circle me-2"></i>图标下载策略</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <h6 class="text-primary"><i class="bi bi-1-circle me-2"></i>HTML解析</h6>
                                <ul class="list-unstyled small">
                                    <li><i class="bi bi-check text-success me-1"></i>解析页面link标签</li>
                                    <li><i class="bi bi-check text-success me-1"></i>支持多种图标类型</li>
                                    <li><i class="bi bi-check text-success me-1"></i>优先PNG格式</li>
                                    <li><i class="bi bi-check text-success me-1"></i>Apple Touch Icon</li>
                                </ul>
                            </div>
                            <div class="col-md-4">
                                <h6 class="text-primary"><i class="bi bi-2-circle me-2"></i>标准路径</h6>
                                <ul class="list-unstyled small">
                                    <li><i class="bi bi-check text-success me-1"></i>/favicon.ico</li>
                                    <li><i class="bi bi-check text-success me-1"></i>/favicon.png</li>
                                    <li><i class="bi bi-check text-success me-1"></i>/apple-touch-icon.png</li>
                                    <li><i class="bi bi-check text-success me-1"></i>多种尺寸支持</li>
                                </ul>
                            </div>
                            <div class="col-md-4">
                                <h6 class="text-primary"><i class="bi bi-3-circle me-2"></i>第三方API</h6>
                                <ul class="list-unstyled small">
                                    <li><i class="bi bi-check text-success me-1"></i>Google Favicon API</li>
                                    <li><i class="bi bi-check text-success me-1"></i>GitHub API</li>
                                    <li><i class="bi bi-check text-success me-1"></i>IconHorse API</li>
                                    <li><i class="bi bi-check text-success me-1"></i>多重重试机制</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 错误日志 -->
            @if (updateResult != null && updateResult.ErrorMessages.Any())
            {
                <div class="col-12">
                    <div class="card border-danger">
                        <div class="card-header bg-danger text-white">
                            <h6 class="mb-0"><i class="bi bi-exclamation-triangle me-2"></i>错误日志</h6>
                        </div>
                        <div class="card-body">
                            <div class="accordion" id="errorAccordion">
                                <div class="accordion-item">
                                    <h2 class="accordion-header">
                                        <button class="accordion-button collapsed" type="button" 
                                                data-bs-toggle="collapse" data-bs-target="#errorDetails">
                                            错误详情 (@updateResult.ErrorMessages.Count 项)
                                        </button>
                                    </h2>
                                    <div id="errorDetails" class="accordion-collapse collapse" 
                                         data-bs-parent="#errorAccordion">
                                        <div class="accordion-body">
                                            @foreach (var error in updateResult.ErrorMessages)
                                            {
                                                <div class="alert alert-danger small mb-2">
                                                    <i class="bi bi-exclamation-circle me-2"></i>@error
                                                </div>
                                            }
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            }
        </div>
    </div>
</div>

@code {
    /// <summary>
    /// 是否正在更新图标
    /// </summary>
    private bool isUpdating = false;

    /// <summary>
    /// 是否正在更新默认网站图标
    /// </summary>
    private bool isUpdatingDefault = false;

    /// <summary>
    /// 是否正在清理
    /// </summary>
    private bool isCleaning = false;

    /// <summary>
    /// 是否正在生成默认图标
    /// </summary>
    private bool isGenerating = false;

    /// <summary>
    /// 更新结果
    /// </summary>
    private IconUpdateResult? updateResult;

    /// <summary>
    /// 操作消息
    /// </summary>
    private string operationMessage = "";

    /// <summary>
    /// 操作是否成功
    /// </summary>
    private bool isOperationSuccess = false;

    /// <summary>
    /// 批量更新图标
    /// </summary>
    private async Task BatchUpdateIcons()
    {
        isUpdating = true;
        operationMessage = "";
        StateHasChanged();

        try
        {
            Logger.LogInformation("开始批量更新网站图标");
            
            updateResult = await IconService.BatchUpdateIconsAsync();
            
            operationMessage = $"批量更新完成！总计 {updateResult.TotalCount} 个网站，" +
                              $"成功 {updateResult.SuccessCount} 个，" +
                              $"失败 {updateResult.FailureCount} 个，" +
                              $"使用默认图标 {updateResult.DefaultIconCount} 个。";
            isOperationSuccess = true;
            
            Logger.LogInformation("批量更新完成: {Message}", operationMessage);
        }
        catch (Exception ex)
        {
            operationMessage = $"批量更新失败: {ex.Message}";
            isOperationSuccess = false;
            Logger.LogError(ex, "批量更新图标时发生错误");
        }
        finally
        {
            isUpdating = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 更新默认网站图标到本地存储
    /// </summary>
    private async Task UpdateDefaultWebsiteIcons()
    {
        isUpdatingDefault = true;
        operationMessage = "";
        StateHasChanged();

        try
        {
            Logger.LogInformation("开始更新默认网站图标到本地存储");
            
            var success = await DataSeedService.UpdateDefaultWebsiteIconsAsync();
            
            if (success)
            {
                operationMessage = "默认网站图标更新完成！所有默认网站的图标已下载到本地存储。";
                isOperationSuccess = true;
                Logger.LogInformation("默认网站图标更新成功");
            }
            else
            {
                operationMessage = "默认网站图标更新失败，请查看日志了解详细信息。";
                isOperationSuccess = false;
                Logger.LogWarning("默认网站图标更新失败");
            }
        }
        catch (Exception ex)
        {
            operationMessage = $"更新默认网站图标失败: {ex.Message}";
            isOperationSuccess = false;
            Logger.LogError(ex, "更新默认网站图标时发生错误");
        }
        finally
        {
            isUpdatingDefault = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 清理未使用的图标
    /// </summary>
    private async Task CleanupUnusedIcons()
    {
        if (!await JSRuntime.InvokeAsync<bool>("confirm", "确定要清理未使用的图标文件吗？此操作不可撤销。"))
            return;

        isCleaning = true;
        operationMessage = "";
        StateHasChanged();

        try
        {
            Logger.LogInformation("开始清理未使用的图标文件");
            
            var deletedCount = await IconService.CleanupUnusedIconsAsync();
            
            operationMessage = $"清理完成！删除了 {deletedCount} 个未使用的图标文件。";
            isOperationSuccess = true;
            
            Logger.LogInformation("清理完成: 删除了 {Count} 个文件", deletedCount);
        }
        catch (Exception ex)
        {
            operationMessage = $"清理失败: {ex.Message}";
            isOperationSuccess = false;
            Logger.LogError(ex, "清理图标文件时发生错误");
        }
        finally
        {
            isCleaning = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 生成默认图标
    /// </summary>
    private async Task GenerateDefaultIcon()
    {
        isGenerating = true;
        operationMessage = "";
        StateHasChanged();

        try
        {
            Logger.LogInformation("开始生成默认图标");
            
            var iconPath = await IconService.GenerateDefaultIconAsync();
            
            operationMessage = $"默认图标生成成功！路径: {iconPath}";
            isOperationSuccess = true;
            
            Logger.LogInformation("默认图标生成成功: {IconPath}", iconPath);
        }
        catch (Exception ex)
        {
            operationMessage = $"生成默认图标失败: {ex.Message}";
            isOperationSuccess = false;
            Logger.LogError(ex, "生成默认图标时发生错误");
        }
        finally
        {
            isGenerating = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 获取进度条样式类
    /// </summary>
    /// <param name="successRate">成功率</param>
    /// <returns>CSS类名</returns>
    private string GetProgressBarClass(double successRate)
    {
        return successRate switch
        {
            >= 80 => "bg-success",
            >= 60 => "bg-warning",
            _ => "bg-danger"
        };
    }
} 